const api = require('../../api/api.js')

Page({
  data: {
    types:[] //  存储所有分类数据
  },
  onReady(){
    // 先判断缓存中是否有数据
    let types = wx.getStorageSync('types')
    if(types){
      this.setData({
        types
      })
      return
    }

    // 发送请求获取数据，并将数据放入缓存中
    Promise.all([
      this.loadHotFilms(),
      this.loadLatestFilms(),
      this.loadFreeFilms()
    ]).then(() => {
      wx.setStorageSync('types', this.data.types)
    })

  },
  // 加载影院热映
  loadHotFilms(){
    return api.loadHotFilms({
      start:0,
      count:6
    }).then(data=>{
      let type = {
        title:data.subject_collection.name,
        list:data.subject_collection_items
      }
      this.setData({
        'types[0]':type
      })
    })
  },
  // 加载近期热门
  loadLatestFilms(){
    return api.loadLatestFilms({
      start:0,
      count:6
    }).then(data=>{
      let type = {
        title:data.subject_collection.name,
        list:data.subject_collection_items
      }
      this.setData({
        'types[1]':type
      })
    })
  },
  // 加载免费在线
  loadFreeFilms(){
    return api.loadFreeFilms({
      start:0,
      count:6
    }).then(data=>{
      let type = {
        title:data.subject_collection.name,
        list:data.subject_collection_items
      }
      this.setData({
        'types[2]':type
      })
    })
  },
  goSearch(){
    wx.navigateTo({
      url: '/pages/search/search',
    })
  }
})